<?php

namespace App\Services\System;
use App\Models\System\SysDictDataModel;
use App\Validate\System\SysDictDataValidate;
use DictUtils;
use Illuminate\Database\Eloquent\Collection;

/**
* 字典数据表 逻辑层 前端API业务分装
* @create 2023-09-26 22:11:23
*/
class SysDictDataService {

    private SysDictDataModel $sysDictDataModel;

    public function __construct(SysDictDataModel $sysDictDataModel) {
        $this->sysDictDataModel = $sysDictDataModel;
    }

    /**
     * 根据条件分页查询字典数据
     * 
     * @param array|SysDictDataModel $dictData 字典数据信息
     * @return 字典数据集合信息
     */
    public function selectDictDataList(array $dictData): Collection {
        return $this->sysDictDataModel->selectDictDataList($dictData);
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     * 
     * @param string $dictType 字典类型
     * @param string $dictValue 字典键值
     * @return string 字典标签
     */
    public function selectDictLabel(string $dictType, string $dictValue) {
        return $this->sysDictDataModel->selectDictLabel($dictType, $dictValue);
    }

    /**
     * 根据字典数据ID查询信息
     * 
     * @param int $dictCode 字典数据ID
     * @return SysDictDataModel 字典数据
     */
    public function selectDictDataById(int $dictCode): SysDictDataModel {
        return $this->sysDictDataModel->selectDictDataById($dictCode);
    }

    /**
     * 批量删除字典数据信息
     * 
     * @param array|int[] dictCodes 需要删除的字典数据ID
     */
    public function deleteDictDataByIds(array $dictCodes): void {
        foreach($dictCodes as $dictCode) {
            $data = $this->selectDictDataById($dictCode);
            $this->sysDictDataModel->deleteDictDataById($dictCode);
            $dictDatas = $this->sysDictDataModel->selectDictDataByType($data->dict_type);
            DictUtils::setDictCache($data->dict_type, $dictDatas);
        }
    }

    /**
     * 新增保存字典数据信息
     * 
     * @param array|SysDictDataModel $data 字典数据信息
     * @return SysDictDataModel 结果
     */
    public function insertDictData(array $data): SysDictDataModel {
        $model = $this->sysDictDataModel->insertDictData($data);
        if ($model) {
            $dictDatas = $this->sysDictDataModel->selectDictDataByType($data['dictType']);
            DictUtils::setDictCache($data['dictType'], $dictDatas);
        }
        return $model;
    }

    /**
     * 修改保存字典数据信息
     * 
     * @param array|SysDictDataModel $data 字典数据信息
     * @return int 结果
     */
    public function updateDictData(array $data): int {
        $row = $this->sysDictDataModel->updateDictData($data);
        if ($row > 0) {
            $dictDatas = $this->sysDictDataModel->selectDictDataByType($data['dictType']);
            DictUtils::setDictCache($data['dictType'], $dictDatas);
        }
        return $row;
    }

}
